package cn.wolfcode.luowowo.comment.services.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQueryObject;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentMongoRepository repository;

    public void save(StrategyComment entity) {
        //填充评论时间
        entity.setCreateTime(new Date());
        repository.save(entity);
    }

    public Page<StrategyComment> query(StrategyCommentQueryObject qo) {
        //spring data分页的页数是从0开始,传入的当前页需要-1
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        return repository.findByDetailId(qo.getDetailId(), pageable);
    }

    public void commentThumbUp(String toId, Long fromId) {
        //1.根据id查询评论对象
        Optional<StrategyComment> op = repository.findById(toId);
        op.ifPresent(comment -> {
            //2.获取当前评论点赞集合
            List<Long> thumbuplist = comment.getThumbuplist();
            //3.判断当前点赞列表中是否含有当前点击用户
            if (thumbuplist.contains(fromId)) {
                //取消
                thumbuplist.remove(fromId);
            } else {
                //点赞
                thumbuplist.add(fromId);
            }
            comment.setThumbupnum(thumbuplist.size());
            //4.保存到mongodb中
            repository.save(comment);
        });
        /*StrategyComment comment = op.get();
        //2.获取当前评论点赞集合
        List<Long> thumbuplist = comment.getThumbuplist();
        //3.判断当前点赞列表中是否含有当前点击用户
        if (thumbuplist.contains(fromId)) {
            //取消
            thumbuplist.remove(fromId);
        } else {
            //点赞
            thumbuplist.add(fromId);
        }
        comment.setThumbupnum(thumbuplist.size());
        //4.保证到mongodb中
        repository.save(comment);*/
    }
}
